package com.suray.system.run.lifter;

import com.suray.basic.wcs.plc.enums.Network;
import com.suray.basic.wcs.plc.pojo.oper.lifter.LifterOper;
import com.suray.system.run.core.ErrorDescription;
import com.suray.system.run.core.LifterInfo;
import com.suray.system.run.core.OfflineDescription;
import com.suray.system.run.data.DeviceTaskInformation;
import com.suray.system.run.data.LifterInformation;
import com.suray.system.run.data.mysql.analyze.MonitorDataStore;
import com.suray.system.run.util.ExecTaskTime;
import com.suray.wcs.service.enums.TaskType;

import java.util.Date;

public class LifterMonitorAction {

    /**
     * 提升机对象
     */
    private LifterOper lifterOper;

    /**
     * 提升机信息
     */
    private LifterInformation lifterInformation;

    /**
     * 数据处理
     */
    private MonitorDataStore monitorDataStore;

    /**
     * 提升机序列号
     */
    private String series;

    public LifterMonitorAction(LifterOper lifterOper, LifterInformation lifterInformation,
                               MonitorDataStore monitorDataStore) {
        this.lifterOper = lifterOper;
        this.lifterInformation = lifterInformation;
        this.monitorDataStore = monitorDataStore;

        series = lifterOper.getSeries();
    }

    public void init() {
        lifterInformation.setDeviceTaskInformation(monitorDataStore.findDeviceTaskInfoData(series));
        lifterInformation.setErrorDescription(monitorDataStore.findErrorDesData(series));
        lifterInformation.setOffLineDescription(monitorDataStore.findOffLineDesData(series));
        lifterInformation.setExecTaskTime(monitorDataStore.findExecTaskData(series));
        checkInitData();
    }

    private void checkInitData() {
        checkDeviceTaskInitData();
        checkExecTaskInitData();
    }

    private void checkDeviceTaskInitData() {
        DeviceTaskInformation deviceTaskInformation = lifterInformation.getDeviceTaskInformation();

        Date date = new Date(System.currentTimeMillis());
        if (!deviceTaskInformation.checkDate(date)) {
            deviceTaskInformation.clearExecTodayTaskTime();
            deviceTaskInformation.setCurDate(date);
            monitorDataStore.updateDeviceTaskInfoData(series);
        }
    }

    private void checkExecTaskInitData() {
        lifterTaskMonitor(lifterOper, lifterInformation);
    }

    private void lifterTaskMonitor(LifterOper lifterOper, LifterInformation lifterInformation) {
        checkDeviceTaskInitData();

        int taskNo = lifterOper.getHoistCurrentTaskNo();
        if (lifterInformation.getExecTaskTime() == null) {
            //提升机目前尚未检测到任务，进行任务检测
            if (taskNo != 0) {
                //提升机检测到任务
                initExecTaskTime(lifterInformation, taskNo, null);
            }
        } else if (lifterInformation.getExecTaskTime() != null) {
            //提升机目前检测到任务，进行任务跟踪
            if (taskNo != 0) {
                //提升机有正在执行的任务
                if (lifterInformation.getExecTaskTime().getTaskId() == taskNo) {
                    //同一个任务
                } else {
                    //不是同一个任务，任务做结束处理
                    endExecTaskTime(lifterInformation);
                }
            } else {
                //提升机没有正在执行的任务
                endExecTaskTime(lifterInformation);
            }
        }
    }

    /**
     * 结束任务
     * @param lifterInformation
     */
    private void endExecTaskTime(LifterInformation lifterInformation) {
        lifterInformation.getExecTaskTime().setEndTime(new Date(System.currentTimeMillis()));
        monitorDataStore.updateExecTaskData(series);
        long taskTime = lifterInformation.getExecTaskTime().getExecTaskTime();
        lifterInformation.getDeviceTaskInformation().addExecTodayTaskTime(taskTime);
        lifterInformation.getDeviceTaskInformation().addExecAllTaskTime(taskTime);
        lifterInformation.setExecTaskTime(null);
        monitorDataStore.updateDeviceTaskInfoData(series);
    }

    /**
     * 初始化任务信息
     * @param lifterInformation
     * @param taskType
     */
    private void initExecTaskTime(LifterInformation lifterInformation, int taskId, TaskType taskType) {
        ExecTaskTime execTaskTime = monitorDataStore.createExecTaskData(series);
        execTaskTime.setExecTime(new Date(System.currentTimeMillis()));
        execTaskTime.setTaskId(taskId);
        execTaskTime.setTaskType(taskType);
        monitorDataStore.updateExecTaskData(series);
        lifterInformation.setExecTaskTime(execTaskTime);

        lifterInformation.getDeviceTaskInformation().addExecTaskNum();
        monitorDataStore.updateDeviceTaskInfoData(series);
    }

    public void run() {
        lifterMonitor();
        lifterTaskMonitor(lifterOper, lifterInformation);
    }

    private void lifterMonitor() {
        analyzeNormalInformation();
        analyzeErrorInformation();
        analyzeOfflineInformation();
    }

    /**
     * 解析提升机实时数据
     */
    private void analyzeNormalInformation() {
        LifterInfo lifterInfo = lifterInformation.getLifterInfo();

    }

    /**
     * 处理故障信息
     */
    private void analyzeErrorInformation() {
        ErrorDescription errorDescription = lifterInformation.getErrorDescription();

        if (errorDescription != null) {
            if (!lifterOper.isLifterFault()) {
                errorDescription.setEndErrorTime(new Date(System.currentTimeMillis()));
                monitorDataStore.updateErrorDesData(series);
                lifterInformation.setErrorDescription(null);
            }
        } else {
            if (lifterOper.isLifterFault()) {
                if (errorDescription == null) {
                    errorDescription = monitorDataStore.createErrorDesData(series);
//                    errorDescription.setErroring(true);
                    errorDescription.setErrorTime(new Date(System.currentTimeMillis()));
                    errorDescription.setErrorLocation(lifterOper.getLocation().toString());
                    errorDescription.setErrorMessage(getLifterErrorMessage(lifterOper));
                    int taskNo = lifterOper.getHoistCurrentTaskNo();
                    if (taskNo != 0) {
                        errorDescription.setErrorTaskId(String.valueOf(taskNo));
                    }
                    monitorDataStore.updateErrorDesData(series);
                    lifterInformation.setErrorDescription(errorDescription);
                }
            }
        }
    }

    /**
     * 获取提升机异常信息
     * @param lifterOper
     * @return
     */
    private String getLifterErrorMessage(LifterOper lifterOper) {
        StringBuffer sb = new StringBuffer();

        if (lifterOper.overFrontLimit()) {
            sb.append("提升机前限位超限!");
        }

        if (lifterOper.overBackLimit()) {
            sb.append("提升机后限位超限!");
        }

        if (lifterOper.overUpLimit()) {
            sb.append("提升机上限位超限!");
        }

        if (lifterOper.overDownLimit()) {
            sb.append("提升机下限位超限!");
        }

        if (lifterOper.scanFault()) {
            sb.append("扫码读取故障!");
        }

        if (lifterOper.scanNumRangeFault()) {
            sb.append("扫码数值范围错误!");
        }

        if (lifterOper.servoFault()) {
            sb.append("伺服报警!");
        }

        if (lifterOper.lifterTaskNoIllegal()) {
            sb.append("提升机任务字非法!");
        }

        if (lifterOper.noCargoStartLocation()) {
            sb.append("提升机起始位置无货!");
        }

        if (lifterOper.hasCargoEndLocation()) {
            sb.append("提升机终点位置有货!");
        }

        if (lifterOper.hasCargoInnerLifter()) {
            sb.append("提升机内有货!");
        }

        if (lifterOper.rgvNotArrived()) {
            sb.append("小车未到位!");
        }

        if (lifterOper.rgvNotLeave()) {
            sb.append("小车未驶离!");
        }

        if (lifterOper.lifterOverChainFrontLimit()) {
            sb.append("提升机内链条机前边缘超限!");
        }

        if (lifterOper.lifterOverChainBackLimit()) {
            sb.append("提升机内链条机后边缘超限!");
        }

        if (lifterOper.overConnectChainLimit()) {
            sb.append("对接链条机边缘超限!");
        }

        if (lifterOper.notReadyHoist()) {
            sb.append("提升机未就绪wcs下发任务!");
        }

        if (lifterOper.lockProblem()) {
            sb.append("wcs锁定失败!");
        }

        if (lifterOper.unlockProblem()) {
            sb.append("解锁失败!");
        }

        if (lifterOper.disconnect()) {
            sb.append("与主控断开!");
        }

        if (lifterOper.chainFault()) {
            sb.append("链条机故障!");
        }

        if (lifterOper.rollerTableFault()) {
            sb.append("辊道机故障!");
        }

        if (lifterOper.transplantLiftFailure()) {
            sb.append("移栽升降机故障!");
        }

        return sb.toString();
    }

    /**
     * 处理离线信息
     */
    private void analyzeOfflineInformation() {
        OfflineDescription offLineDescription = lifterInformation.getOffLineDescription();

        if (offLineDescription != null) {
            if (lifterOper.getPlc().getPlcStatus() == Network.ON_LINE) {
                offLineDescription.setOffLineEndDate(new Date(System.currentTimeMillis()));
                monitorDataStore.updateOffLineDesData(series);
            }

            if (offLineDescription.getOffLineEndDate() != null) {
                lifterInformation.setOffLineDescription(null);
            }
        } else {
            if (lifterOper.getPlc().getPlcStatus() == Network.OFF_LINE) {
                OfflineDescription offlineDescription = monitorDataStore.createOffLineDesData(series);
                offlineDescription.setOffLineStartDate(new Date(System.currentTimeMillis()));
                monitorDataStore.updateOffLineDesData(series);
                lifterInformation.setOffLineDescription(offlineDescription);
            }
        }

    }

}
